//const returnModel = require('../model/ReturnModel')
const { getTodoList, add, edit, del } = require('../service/todolist')
const router = require('koa-router')()



router.get('/todolist', async (ctx, next) => {
  try {
    listData = await getTodoList()   //getListInCache()
    listData = listData.map(item => {
      item.stateText = item.state == 0 ? '未完成' : '完成'
      return item
    }
    )
  }
  catch (e) {
    console.log(e)
  }
  ctx.body =
  {
    "errno": 0,
    "data": listData

    // [
    //   {
    //     "itemname": "test1",
    //     "state": 0
    //   },
    //   {
    //     "itemname": "test2",
    //     "state": 0
    //   },
    //   {
    //     "itemname": "test3",
    //     "state": 0
    //   },
    // ]
  }


})

router.post('/todolist', async (ctx, next) => {

  const body = ctx.request.body
  const result = await add(body)



  // console.log(body)
  // listData.push(body)
  ctx.body =
  {
    "errno": 0,
    "data": result
  }
})

router.put('/todolist', async (ctx, next) => {

  const body = ctx.request.body
  // const { i } = ctx.params //解构赋值
  // listData[i] = body;

  const result = await edit(body)
  ctx.body =
  {
    "errno": 0,
    "data": result
  }
})



router.delete('/todolist', async (ctx, next) => {

  // listData.splice(i, 1)

  const body = ctx.request.body
  const params = ctx.params
  console.log(body)
  console.log(params)
  const { id } = body

  const result = await del(id)
  //const body = ctx.request.body
  //  ctx.body = '删除成功！！'  //errno,,status, message

  ctx.body =
  {
    "errno": 0,
    "data": result
  }
})
module.exports = router